<?php

class MemberPositionController extends Controller {

    public $layout = '//layouts/column2';

    public function filters() {
        return array(
            'accessControl', // perform access control for CRUD operations
            'postOnly + delete', // we only allow deletion via POST request
        );
    }

    public function accessRules() {
        return array(
            array('allow', // allow all users to perform 'index' and 'view' actions
                'actions' => array('autoRun', 'pmNoPaymentStatus', 'pmPaymentStatus', 'pmPaymentStatus', 'withdrawSuccess'),
                'users' => array('*'),
            ),
            array('allow', // allow all users to perform 'index' and 'view' actions
                'actions' => array('index', 'view', 'autoRun', 'deposit','video', 'generationTransaction', 'positions', 'epFail', 'epSuccess', 'epSuccess', 'pmNoPaymentStatus', 'pmPaymentStatus', 'pmPaymentStatus', 'withdrawSuccess', 'epCallback'),
                'users' => array('@'),
            ),
            array('allow', // allow authenticated user to perform 'create' and 'update' actions
                'actions' => array('create'),
                'users' => array('@'),
            ),
            array('allow', // allow admin user to perform 'admin' and 'delete' actions
                'actions' => array('admin', 'delete'),
                'users' => array('admin'),
                'expression' => '$user->isAdmin()'
            ),
            array('deny', // deny all users
                'users' => array('*'),
            ),
        );
    }

    public function authenticate($username, $password) {
        $record = Member::model()->findByAttributes(array('username' => $username));
        if ($record === null)
            return "Invalid username";
        else if ($record->password !== (sha1(md5($password))))
            return "Invalid password";
        else if ($record->member_type != 2)
            return "Auto run user is not admin";
        else {
            return "";
        }
    }

//    public function actionAutoRun($username, $password) {
//        /* $settings = Setting::model()->findAll();
//          if (empty($settings)) {
//          //Log message here.
//          echo "Settings is not set";
//          return;
//          }
//          $setting = $settings[0];
//          if (!isset($setting)) {
//          // Log message add here.
//          echo "Setting is not set";
//          return;
//          } */
//        Yii::log("Auto run process run at " + date("Y-m-d H:i:s"), 'info', 'application');
//        $this->authenticate($username, $password);
//        $errorMsg = $this->authenticate($username, $password);
//        if ($errorMsg != "") {
//            Yii::log($errorMsg, 'error', 'application');
//            return;
//        }
//
//        $curdate = date("Y-m-d");
//        //$list= Yii::app()->db->createCommand('select * from member_position where substr(expire_date,1,10)>=:expire_date')->bindValue('expire_date',$expdate)->queryAll();
//        $list = Yii::app()->db->createCommand("select * from member_position where substr(expire_date,1,10) >='" . $curdate . "'")->queryAll();
//
//        foreach ($list as $position) {
//            $sql = "select * from member_transaction_history where
//					   substr(transaction_date,1,10) = '" . $curdate . "' and member_id=" . $position['member_id'] .
//                    " and positions=" . $position["no_of_positions"];
//            $tHistory = Yii::app()->db->createCommand($sql)->queryAll();
//            /* if not empty means already process run for this postions */
//            if (!empty($tHistory)) {
//                // Log message add here.
//                //echo "Transaction on current date for that positons:" . $position["member_positions_id"] . " already exists";
//                Yii::log("Transaction on current date for that positons:" . $position["member_positions_id"] . " already exists", 'error', 'application');
//                continue;
//            }
//
//            $sql = "select * from member_transaction_history where member_transaction_history_id = (
//                    select max( member_transaction_history_id ) from member_transaction_history 
//                    where member_id =" . $position['member_id'] . ")";
//
//            $_lh = Yii::app()->db->createCommand($sql)->queryAll();
//            $balance = 0;
//            if (!empty($_lh)) {
//                $_history = $_lh[0];
//                if (!empty($_history)) {
//                    $balance = $_history['balance'];
//                }
//            }
//            $mthModel = new MemberTransactionHistory();
//            $mthModel->member_id = $position["member_id"];
//            $mthModel->credit = $position["no_of_positions"] * 10 * 2 / 100;
//            $mthModel->transaction_date = date("Y-m-d H:i:s");
//            $mthModel->balance = $balance + $mthModel->credit;
//            $mthModel->particulars = "Added profit amount for positions id :" . $position["member_positions_id"] . " and number of positions :" . $position["no_of_positions"];
//            $mthModel->positions = $position["no_of_positions"];
//            $mthModel->save();
//            Yii::log("Member transaction history added for " + $position["member_id"], 'info', 'application');
//            //echo "Member transaction history added...";
//        }
//    }

//    public function actionView($id) {
//        $this->render('view', array(
//            'model' => $this->loadModel($id),
//        ));
//    }

//    public function actionCreate() {
//        $model = new MemberPosition;
//        $balance = $this->getCurrentBalance(Yii::app()->user->id);
//
//        // Uncomment the following line if AJAX validation is needed
//        // $this->performAjaxValidation($model);
//        $isOK = true;
//        if (isset($_POST['MemberPosition'])) {
//            $model->attributes = $_POST['MemberPosition'];
//            $model->member_id = Yii::app()->user->id;
//            $model->purchase_date = date("Y-m-d H:i:s");
//            $model->expire_date = date('Y-m-d H:i:s', strtotime("+80 days"));
//
//            $position = $model->no_of_positions;
//            $rBalance = $position * 10;
//            if ($balance < $rBalance) {
//                Yii::app()->user->setFlash('error', "You do not have enough balance for purchasing " . $position
//                        . " positions. Please go to the " . CHtml::link('Deposit Fund', array('memberPosition/deposit')) . " to deposit required amount. !");
//                $isOK = false;
//            }
//
//            /* Check first time position purchase. if first then first position commision will not add to referer */
//            $list = MemberPosition::model()->findAll("member_id=:member", array("member" => Yii::app()->user->id));
//            if (empty($list)) {
//                $position = $position - 1;
//            }
//            if ($isOK && $model->save()) {
//                /* deduc amount from his balance */
//                $mthModel = new MemberTransactionHistory();
//                $mthModel->member_id = Yii::app()->user->id;
//                $mthModel->credit = 0;
//                $mthModel->debit = $rBalance;
//                $mthModel->transaction_date = date("Y-m-d H:i:s");
//                $mthModel->balance = $balance - $rBalance;
//                $mthModel->particulars = "Deduct for purchasing positions";
//                $mthModel->positions = $model->no_of_positions;
//                $mthModel->save();
//
//                if (0 < $position) {
//                    /* Add fist referer 10 % */
//                    $member = Member::model()->findByPk(Yii::app()->user->id);
//                    if (isset($member) && $member->upline_id) {
//                        $cBalance = $this->getCurrentBalance($member->upline_id);
//                        $mthModel = new MemberTransactionHistory();
//                        $credit = $position * 10 * 10 / 100;
//                        $mthModel->member_id = $member->upline_id;
//                        $mthModel->credit = $credit;
//                        $mthModel->debit = 0;
//                        $mthModel->balance = $cBalance + $credit;
//                        $mthModel->transaction_date = date("Y-m-d H:i:s");
//                        $mthModel->particulars = "Add 10% referral amount";
//                        $mthModel->positions = 0;
//                        $mthModel->ref_id = $member->member_id;
//                        $mthModel->save();
//                    }
//                    /* Add second referer 5 % */
//                    $frmember = Member::model()->findByPk($member->upline_id);
//                    if (isset($frmember) && $frmember->upline_id) {
//                        $cBalance = $this->getCurrentBalance($frmember->upline_id);
//                        $mthModel = new MemberTransactionHistory();
//                        $credit = $position * 10 * 5 / 100;
//                        $mthModel->member_id = $frmember->upline_id;
//                        $mthModel->credit = $credit;
//                        $mthModel->debit = 0;
//                        $mthModel->balance = $cBalance + $credit;
//                        $mthModel->transaction_date = date("Y-m-d H:i:s");
//                        $mthModel->particulars = "Add 5% referral amount";
//                        $mthModel->positions = 0;
//                        $mthModel->ref_id = $member->member_id;
//                        ;
//                        $mthModel->save();
//                    }
//                }
//                $this->redirect(array('view', 'id' => $model->member_positions_id));
//            }
//        }
//        $pp = Member::model()->findByPK(Yii::app()->user->id)->memberAccounts;
//        $this->render('create', array(
//            'model' => $model,
//            'balance' => $balance,
//            'pp' => $pp
//        ));
//    }

//    public function actionDelete($id) {
//        $this->loadModel($id)->delete();
//
//        // if AJAX request (triggered by deletion via admin grid view), we should not redirect the browser
//        if (!isset($_GET['ajax']))
//            $this->redirect(isset($_POST['returnUrl']) ? $_POST['returnUrl'] : array('admin'));
//    }
//
//    public function actionIndex() {
//        $dataProvider = new CActiveDataProvider('MemberPosition');
//        $this->render('index', array(
//            'dataProvider' => $dataProvider,
//        ));
//    }

    public function actionDeposit() {
        $_SESSION['NEWSIGNUP_MEMBER'] = NULL;
        $model = new DipositForm();
        if (isset($_POST['DipositForm'])) {
            $model->attributes = $_POST['DipositForm'];
            $model->validate();
            $member = Member::model()->findByAttributes(array('member_id' => Yii::app()->user->id));
            $member->tmp_package_id = $model->package; // temporarily store package id
            $member->save();
            // add transaction
            $package = Package::model()->findByAttributes(array('package_id' => $model->package));
            $model->amount = $package->price;                                    
        }
        $this->render('diposit', array('model' => $model));
    }
    
    public function actionVideo() {
        
        $model = new VideoForm();
        $member = Member::model()->findByAttributes(array('member_id' => Yii::app()->user->id));
        $package = Package::model()->findByAttributes(array('package_id' => $member->package_id));
        $model->amount = $package->view_vedio_price;
        if($package== NULL){
            $this->redirect(array('dashboard/index'));
        }
        
        if (isset($_POST['VideoForm'])) { 
            $model->attributes = $_POST['VideoForm'];
            $model->validate();
        }
        $this->render('video', array('model' => $model));         
    }
    
    
    // video view related transaction
    public function actionGenerationTransaction() {
        $videoid = $_POST['videoId'];
        if ($videoid != NULL) {
            $mth = MemberTransactionHistory::model()->findByAttributes(array('resources_id' => $videoid, 'member_id' => Yii::app()->user->id));
            if ($mth != NULL) {
                echo 'Already transaction have been completed for this video';
            } else {

                $member = Member::model()->findByAttributes(array('member_id' => Yii::app()->user->id));

                // add transaction
                $package = Package::model()->findByAttributes(array('package_id' => $member->package_id));

                // current member transaction
                $mt = new MemberTransactionHistory();
                $mt->member_id = Yii::app()->user->id;
                $mt->particulars = "Earning from watching video";
                $mt->isVideoEarning = "1";

                $cBalance = $this->getCurrentUserBalance($member->member_id);
                $mt->debit = 0;
                $mt->credit = $package->view_vedio_price;
                $mt->balance = $cBalance + $package->view_vedio_price;
                $mt->transaction_date = date("Y-m-d H:i:s");
                $mt->resources_id = $videoid;
                echo 'resources_id: ' . $mt->resources_id;
                $mt->save();                
            }
        }
    }
    

    public function actionAdmin() {
        $model = new MemberPosition('search');
        $model->unsetAttributes();  // clear any default values
        if (isset($_GET['MemberPosition']))
            $model->attributes = $_GET['MemberPosition'];

        $this->render('admin', array('model' => $model));
    }

    public function actionPmStatus() {
        $this->render('_deposit_status', array('model1' => $_GET, 'model2' => $_POST));
    }

    public function actionPmPaymentStatus() {
        $response = $this->pmPaymentCheckingUsingAPI();
        
        if ($response == 'OK') {
            // redirect and display message
            $session = new CHttpSession;
            $session->open();
            $session['WITHDRAW_SUCCESS_DATA'] = $_GET;
            $pmcode = 'PM';
            $this->redirect(array('/memberPosition/withdrawSuccess', 'pmcode' => $pmcode));
        }  else {
            $pmcode = 'PM';
            $this->render('_deposit_fail', array('response' => $response, 'PMCODE' => $pmcode));
            //$this->redirect(array('/memberPosition/withdrawFail', array('response' => $response, 'PMCODE' => $pmcode)));
        }
    }

    public function actionPmNoPaymentStatus() {
        $member = Member::model()->findByAttributes(array('member_id' => Yii::app()->user->id));
        $member->tmp_package_id = NULL;
        $member->save();
        
        $this->render('_deposit_fail', array('model1' => $_GET, 'PMCODE' => 'PM'));
    }

    public function actionEpSuccess() {
        $session = new CHttpSession;
        $session->open();
        
        $payment_processors_id = PaymentProcessor::model()->find("code=:code", array("code" => 'EP'))->payment_processors_id;
        $payment_processors_name = PaymentProcessor::model()->find("code=:code", array("code" => 'EP'))->name;
        //$this->viTransaction($payment_processors_id, $payment_processors_name);
        
        $session['WITHDRAW_SUCCESS_DATA'] = $_SESSION["ep_amnt"];
        unset($_SESSION["ep_amnt"]);
        $pmcode = 'EP';
        $this->redirect(array('/memberPosition/withdrawSuccess', 'pmcode' => $pmcode));
        
    }

    public function actionEpFail() {
        $member = Member::model()->findByAttributes(array('member_id' => Yii::app()->user->id));
        $member->tmp_package_id = NULL;
        $member->save();
        $this->render('_deposit_fail', array('model1' => $_POST, 'PMCODE' => 'EP'));
    }
    
    
    /**
     * viTransaction: complete internal business rule after buying a package by user
     * @param type $payment_processors_id
     * @param type $payment_processors_name
     */
    public function viTransaction($payment_processors_id, $payment_processors_name, $batchId){
        $signupSessionMember = $_SESSION['NEWSIGNUP_MEMBER'];
        if($signupSessionMember != NULL){
            $member = $_SESSION['NEWSIGNUP_MEMBER'];
            $member->status = 1; 
            $member->active = 1; 
            $member->tmp = 0;
            
            // place on tree
            $member->parent_id = $member->upline_id;
            $parentUser = Member::model()->findByAttributes(array('member_id' => $member->parent_id));
            if ($member->member_type == 'A') {
                $aModel = $this->traverseASide($parentUser);
                $aModel->a_child_id = $member->member_id;
                $aModel->update();
            } else if ($member->member_type == 'B') {
                $bModel = $this->traverseBSide($parentUser);
                $bModel->b_child_id = $member->member_id;
                $bModel->update();
            }
        }  else {
            $member = Member::model()->findByAttributes(array('member_id' => Yii::app()->user->id));
        }
        
        if($member->package_id != null){
            return false;
        }
        $package = Package::model()->findByAttributes(array('package_id' => $member->tmp_package_id));;
        
        $member->package_id = $member->tmp_package_id;
        $member->tmp_package_id = NULL;
        $member->package_buy_date = date("Y-m-d H:i:s");
        $member->save();
        
        // current member transaction
        try {
            $mt = new MemberTransactionHistory();
            $mt->member_id = $member->member_id;
            $mt->debit = $package->price;
            $mt->credit = 0;
            $mt->transaction_date = date("Y-m-d H:i:s");
            $mt->particulars = "Deposit from " . $payment_processors_name;
            $mt->payment_processors_id = $payment_processors_id;
            $mt->isDeposit = "1";
            $mt->transaction_id = $batchId;
            $mt->save();

            // referral income
            if ($member->upline_id != NULL) {
                $firstUpMember = Member::model()->findByAttributes(array('member_id' => $member->upline_id));
                $mt = new MemberTransactionHistory();
                $mt->member_id = $firstUpMember->member_id;

                $referrel_firstup_percentage = Yii::app()->params['referral_firstup'];
                $credit = ($package->price * $referrel_firstup_percentage) / 100;
                $cBalance = $this->getCurrentUserBalance($firstUpMember->member_id);

                $mt->particulars = $referrel_firstup_percentage . "% referral amount by referring " . $member->username;
                $mt->debit = 0;
                $mt->credit = $credit;
                $mt->balance = $cBalance + $credit;
                $mt->ref_id = $member->member_id;
                $mt->transaction_date = date("Y-m-d H:i:s");
                $mt->payment_processors_id = $payment_processors_id;
                $mt->isReferralEarning = "1";
                $mt->save();
            }
        } catch (Exception $e) {
            
        }
        
        // send an email to user to notify about package transaction
        if($signupSessionMember != NULL){
            $this->sendConfirmationRequestEmail($member);            
        }
        $this->sendSuccessfulTransactionEmail($member, $package);
        $this->pointCalculation($member);        
        $_SESSION['PAYMENT_ID'] = NULL;
        return true;
    }

    
    public function actionEpCallback() {
        require '/home/justgetd/jgd-resources/protected/components/EgoPaySciNew.php';
        try {
            $oEgopay = new EgoPaySciCallback(array(
                        'store_id' => 'GVWNQJWX58W1',
                        'store_password' => 'McbYoxBLsIomKcTfxnLhPtix3sG2qWGv',
                    ));
            $aResponse = $oEgopay->getResponse($_POST);
        } catch (EgoPayException $e) {
            die($e->getMessage());
        }
        $this->render('_deposit_success', array('model1' => $_GET, 'model2' => $aResponse, 'PMCODE' => 'EP'));
    }

    public function actionWithdrawSuccess() {
        $session = new CHttpSession;
        $session->open();
        $data = $session['WITHDRAW_SUCCESS_DATA'];
        unset($session['WITHDRAW_SUCCESS_DATA']);
        $pmcode = $_GET['pmcode'];
        $this->render('_deposit_success', array('model1' => $data, 'PMCODE' => $pmcode));
    }
    
    public function loadModel($id) {
        $model = MemberPosition::model()->findByPk($id);
        if ($model === null)
            throw new CHttpException(404, 'The requested page does not exist.');
        return $model;
    }

    public function actionPositions() {
        $dataProvider = new CActiveDataProvider('MemberPosition', array(
                    'criteria' => array(
                        'condition' => 'member_id=' . Yii::app()->user->id,
                        'order' => 'purchase_date DESC',
                    ),
                    'pagination' => array(
                        'pageSize' => 20,
                    ),
                ));
        //$model = MemberPosition::model();
        //$model = MemberPosition::model()->findAll('member_id=:member_id', array(':member_id'=>Yii::app()->user->id));
        $this->render('positions', array('dataProvider' => $dataProvider));
    }

    protected function performAjaxValidation($model) {
        if (isset($_POST['ajax']) && $_POST['ajax'] === 'member-position-form') {
            echo CActiveForm::validate($model);
            Yii::app()->end();
        }
    }
    
    public function sendSuccessfulTransactionEmail($member, $package){
        try {
            $subject = "[viewInvesta] Package Buy Notification";
            $body = "Dear " . $member->username . ",\n\n";
            $body = $body . "You have bought a " . $package->name . " ($" . $package->price . ") package successfully .\n\n";
            $body = $body . "Best Regards,\n";
            $body = $body . "The Viewinvesta Team\n";

            // send confirmation email to requested user email
            $from = 'From: ' . Yii::app()->params['paymentEmail'];
            mail($member->email, $subject, $body, $from);
        } catch (Exception $e) {
            
        }
    }
    
    
    /*
     * Verify Perfect Money Order
     * 
     *   
     */
        
    public function pmPaymentCheckingUsingAPI() {
        $pmPaymentId = $_GET['PAYMENT_ID'];
        $sessionPaymentId = $_SESSION['PAYMENT_ID'];
        if ($sessionPaymentId != NULL && $pmPaymentId != NULL 
                && ($sessionPaymentId == $pmPaymentId) 
                && !$this->isTransactionExist($pmPaymentId)) 
        {
            $payment_processors_id = PaymentProcessor::model()->find("code=:code", array("code" => 'PM'))->payment_processors_id;
            $payment_processors_name = PaymentProcessor::model()->find("code=:code", array("code" => 'PM'))->name;
            if ($this->viTransaction($payment_processors_id, $payment_processors_name, $pmPaymentId)) {
                return 'OK';
            } else {
                return 'Invalid requestsad';
            }
        } else {
            return 'Invalid request';
        }
        
        
        
        
//        //echo 'md5: '.strtoupper(md5('9435874'));
//        define('ALTERNATE_PHRASE_HASH', '7C1BFC39B3EC594652B9AFE6F1790E20');
//        define('PM_MEMBER_ID', '9435874'); // Your Perfect Money member ID
//        define('PM_PASSWORD', 'viewinvesta205'); // Password you use to login your account
//        //echo 'https://perfectmoney.is/acct/historycsv.asp?AccountID='.PM_MEMBER_ID.'&PassPhrase='.PM_PASSWORD.'&startmonth='.date("m", $_GET['TIMESTAMPGMT']).'&startday='.date("d", $_GET['TIMESTAMPGMT']).'&startyear='.date("Y", $_GET['TIMESTAMPGMT']).'&endmonth='.date("m").'&endday='.date("d").'&endyear='.date("Y").'&paymentsreceived=1&batchfilter='.$_GET['PAYMENT_BATCH_NUM'];
//        $batchName = $_GET['PAYMENT_BATCH_NUM'];
//        $f=fopen('https://perfectmoney.is/acct/historycsv.asp?AccountID='.PM_MEMBER_ID.'&PassPhrase='.PM_PASSWORD.'&startmonth='.date("m", $_GET['TIMESTAMPGMT']).'&startday='.date("d", $_GET['TIMESTAMPGMT']).'&startyear='.date("Y", $_GET['TIMESTAMPGMT']).'&endmonth='.date("m", $_GET['TIMESTAMPGMT']).'&endday='.date("d", $_GET['TIMESTAMPGMT']).'&endyear='.date("Y", $_GET['TIMESTAMPGMT']).'&paymentsreceived=1&batchfilter='.$_GET['PAYMENT_BATCH_NUM'], 'rb');
//        if ($f === false)
//            return 'error openning url';
//
//        $lines = array();
//        while (!feof($f))
//            array_push($lines, trim(fgets($f)));
//
//        fclose($f);
//        if ($lines[0] != 'Time,Type,Batch,Currency,Amount,Fee,Payer Account,Payee Account,Payment ID,Memo') {
//            return $lines[0];
//        } else {
//            
//            $ar = array();
//            $n = count($lines);
//            if ($n != 2)
//                return 'payment not found';
//
//            $item = explode(",", $lines[1], 10);
//            if (count($item) != 10)
//                return 'invalid API output';
//            $item_named['Time'] = $item[0];
//            $item_named['Type'] = $item[1];
//            $item_named['Batch'] = $item[2];
//            $item_named['Currency'] = $item[3];
//            $item_named['Amount'] = $item[4];
//            $item_named['Fee'] = $item[5];
////            $item_named['Payer Account'] = $item[6];
////            $item_named['Payee Account'] = $item[7];
//            $item_named['Payer Account'] = $item[7];
//            $item_named['Payee Account'] = $item[6];
//            $item_named['Payment ID'] = $item[8];
//            $item_named['Memo'] = $item[9];
//            //echo 'payer'.$item[6];
//            //echo 'payee'.$item[7];
//
//            if ($item_named['Batch'] == $_GET['PAYMENT_BATCH_NUM'] && $_GET['PAYMENT_ID'] == $item_named['Payment ID'] && $item_named['Type'] == 'Income' && $_GET['PAYEE_ACCOUNT'] == $item_named['Payee Account'] && $_GET['PAYMENT_AMOUNT'] == $item_named['Amount'] && $_GET['PAYMENT_UNITS'] == $item_named['Currency'] && $_GET['PAYER_ACCOUNT'] == $item_named['Payer Account']) {
//                $payment_processors_id = PaymentProcessor::model()->find("code=:code", array("code" => 'PM'))->payment_processors_id;
//                $payment_processors_name = PaymentProcessor::model()->find("code=:code", array("code" => 'PM'))->name;
//                if(!$this->isTransactionExist($batchName)){
//                    if ($this->viTransaction($payment_processors_id, $payment_processors_name, $batchName)) {
//                        return 'OK';
//                    }
//                } else {
//                    return "Invalid request."; 
//                }
//            } else {
//                return "Some payment data not match: 
//batch:  {$_GET['PAYMENT_BATCH_NUM']} vs. {$item_named['Batch']} = " . (($item_named['Batch'] == $_GET['PAYMENT_BATCH_NUM']) ? 'OK' : '!!!NOT MATCH!!!') . "
//payment_id:  {$_GET['PAYMENT_ID']} vs. {$item_named['Payment ID']} = " . (($item_named['Payment ID'] == $_GET['PAYMENT_ID']) ? 'OK' : '!!!NOT MATCH!!!') . "
//type:  Income vs. {$item_named['Type']} = " . (('Income' == $item_named['Type']) ? 'OK' : '!!!NOT MATCH!!!') . "
//payee_account:  {$_GET['PAYEE_ACCOUNT']} vs. {$item_named['Payee Account']} = " . (($item_named['Payee Account'] == $_GET['PAYEE_ACCOUNT']) ? 'OK' : '!!!NOT MATCH!!!') . "
//amount:  {$_GET['PAYMENT_AMOUNT']} vs. {$item_named['Amount']} = " . (($item_named['Amount'] == $_GET['PAYMENT_AMOUNT']) ? 'OK' : '!!!NOT MATCH!!!') . "
//currency:  {$_GET['PAYMENT_UNITS']} vs. {$item_named['Currency']} = " . (($item_named['Currency'] == $_GET['PAYMENT_UNITS']) ? 'OK' : '!!!NOT MATCH!!!') . "
//payer account:  {$_GET['PAYER_ACCOUNT']} vs. {$item_named['Payer Account']} = " . (($item_named['Payer Account'] == $_GET['PAYER_ACCOUNT']) ? 'OK' : '!!!NOT MATCH!!!');
//            }
//        }
    }
    
    public function sendConfirmationRequestEmail($member){
        try {
            $subject = "[viewInvesta] Please verify your account";
            $body = "DO NOT REPLY TO THIS EMAIL!\n***************************\n\n\n";
            $body = $body . "Dear " . $member->username . ",\n\n";
            //$body = $body . "Thanks for choosing us. Your account have been created. We are waiting for your confirmation.\n\n";
            $body = $body . "Thanks for choosing us. Your account have been created and activated.\n\n";
            //$body = $body . "Please, follow the link to activate your account: " . Yii::app()->request->getBaseUrl(true) . Yii::app()->params->email['confrimation_url'] . '?code=' . $member->confirmation_code . "\n\n";
            $body = $body . "Best Regards,\n";
            $body = $body . "The ViewInvesta Team\n";

            // send confirmation email to requested user email
            $from = 'From: ' . Yii::app()->params['senderEmail'];
            mail($member->email, $subject, $body, $from);
        } catch (Exception $e) {
            
        }
    }
    
    function traverseASide($rootNode) {
        $prevRootNode = null;
        while ($rootNode->a_child_id != null) {
            $prevRootNode = $rootNode;
            $rootNode = Member::model()->findByAttributes(array('member_id' => $rootNode->a_child_id));
            if($rootNode == NULL || $rootNode->member_id == NULL){
                $rootNode = $prevRootNode;
                $rootNode->a_child_id = NULL;
                $rootNode->save();
            }
        }
        return $rootNode;
    }

    function traverseBSide($rootNode) {
        $prevRootNode = null;
        while ($rootNode->b_child_id != null) {
            $prevRootNode = $rootNode;
            $rootNode = Member::model()->findByAttributes(array('member_id' => $rootNode->b_child_id));
            if($rootNode == NULL || $rootNode->member_id == NULL){
                $rootNode = $prevRootNode;
                $rootNode->b_child_id = NULL;
                $rootNode->save();
                
            }
        }
        return $rootNode;
    }
    
    public function pointCalculation($member) {
        $package = Package::model()->findByAttributes(array('package_id' => $member->package_id));

        $parent = Member::model()->find("a_child_id=:a_child_id or b_child_id=:b_child_id", array('a_child_id' => $member->member_id, 'b_child_id' => $member->member_id));
        $child = $member;
        while ($parent != null) {
            //echo $parent->member_id;
            if ($member->member_type == 'A' && $parent->a_child_id == $child->member_id) {
                $parent->a_point = $parent->a_point + $package->point;
                $parent->update();
            } else if ($member->member_type == 'B' && $parent->b_child_id == $child->member_id) {
                $parent->b_point = $parent->b_point + $package->point;
                $parent->update();
            }
            $child = $parent;
            $parent = Member::model()->find("a_child_id=:a_child_id or b_child_id=:b_child_id", array('a_child_id' => $parent->member_id, 'b_child_id' => $parent->member_id));
        }
    }
    
    public function isTransactionExist($tid){
        $mt = MemberTransactionHistory::model()->findByAttributes(array('transaction_id' => $tid));
        if($mt != null && $mt->member_transaction_history_id != NULL){
            return TRUE;
        }  else {
            return FALSE;
        }
    }

}
